﻿
namespace BasicHostModule.Module
{
    public class TaskBackgroundService : BackgroundService
    {
        /// <summary>
        /// 应用程序运行的时候，调用
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine("后台任务2启动.....");
            //1、死循环实现定时任务
            while (!stoppingToken.IsCancellationRequested)
            {
                DoWork();

                // 2、3s执行一次循环
                await Task.Delay(3000, stoppingToken);
            }
            //return Task.CompletedTask
        }

        private void DoWork()
        {
            Console.WriteLine($"任务2执行：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
        }

        ///// <summary>
        ///// 应用程序停止的时候，调用
        ///// </summary>
        ///// <param name="cancellationToken"></param>
        ///// <returns></returns>
        //public override async Task StartAsync(CancellationToken cancellationToken)
        //{
        //    Console.WriteLine("后台任务2停止.....");
        //    await base.StopAsync(cancellationToken);
        //}

        /// <summary>
        /// 应用程序停止的时候，调用
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("后台任务2停止.....");
            await base.StopAsync(cancellationToken);
        }
    }
}
